package com.dkd.findmyfriends;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class MultiImageChooserActivity extends FragmentActivity implements OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
	private static final String TAG = MultiImageChooserActivity.class.getSimpleName();
	public static final String COL_WIDTH_KEY = "COL_WIDTH";
	public static final String FLURRY_EVENT_ADD_MULTIPLE_IMAGES = "Add multiple images";
	
	private static final int DEFAULT_COLUMN_WIDTH = 120;
	private static final int SELECTED_BG_COLOR = Color.GREEN;
	
	public static final int NOLIMIT = -1;
	public static final String MAX_IMAGES_KEY = "MAX_IMAGES";
	public static final String CURRENT_IMAGES_KEY = "CURRENT_IMAGES";
	public static final String TYPE_KEY = "IMAGE_TYPE";

	private ImageAdapter ia;

	private Cursor imageCursor;
	private int image_id_column_index, image_orient_column_index, contact_image_column_index;
	private int colWidth;

	private static final int CURSORLOADER_GALLERY = 0;
	private static final int CURSORLOADER_CONTACTS = 1;
	

//	private SparseArray<Bitmap> alreadyChosen = new SparseArray<Bitmap>();
//	private SparseArray<Bitmap> images = new SparseArray<Bitmap>(); 

	private SparseBooleanArray checkStatus = new SparseBooleanArray();

	private Button acceptButton;
	private TextView remainingLabel = null;
	private int maxImagesLeft;
	private boolean unlimitedImages = false;

	private GridView gridView;
	private boolean isGallery;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.multiselectorgrid);

		maxImagesLeft = getIntent().getExtras().getInt(MAX_IMAGES_KEY, NOLIMIT);
//		alreadyChosen = getIntent().getExtras().getSparseParcelableArray(CURRENT_IMAGES_KEY);

		unlimitedImages = maxImagesLeft == NOLIMIT;
		if (!unlimitedImages) {
			remainingLabel = (TextView) findViewById(R.id.label_images_left);
			remainingLabel.setVisibility(View.VISIBLE);
			updateLabel();
		}

		acceptButton = (Button) findViewById(R.id.btn_select);
		acceptButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectClicked(v);
			}
		});

		colWidth = getIntent().getIntExtra(COL_WIDTH_KEY, DEFAULT_COLUMN_WIDTH);

		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setColumnWidth(colWidth);
		gridView.setOnItemClickListener(this);

		ia = new ImageAdapter(this);
		gridView.setAdapter(ia);

		LoaderManager.enableDebugLogging(true);
		switch (getIntent().getIntExtra(TYPE_KEY, 0)) {
		case AddPhotosActivity.GALLERY:
			isGallery = true;
			getSupportLoaderManager().initLoader(CURSORLOADER_GALLERY, null, this);			
			break;
		case AddPhotosActivity.CONTACTS:
			isGallery = false;
			getSupportLoaderManager().initLoader(CURSORLOADER_CONTACTS, null, this);			
			break;
		}
	}

	private void updateLabel() {
		if (remainingLabel != null) {
			String text = String.format(getString(R.string.free_version_label), maxImagesLeft);
			remainingLabel.setText(text);
			remainingLabel.setBackgroundColor(Color.parseColor("#33B5E5"));
			if (maxImagesLeft == 0) {
				remainingLabel.setTextColor(Color.RED);
			} else {
				remainingLabel.setTextColor(Color.WHITE);
			}
		}
	}

	public class ImageAdapter extends BaseAdapter {
		private final Matrix m = new Matrix();
		private Canvas canvas;

		public ImageAdapter(Context c) {
		}

		public int getCount() {
			if (imageCursor != null) {
				return imageCursor.getCount();
			} else {
				return 0;
			}
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			if(isGallery) {//return image id
				if(imageCursor.moveToPosition(position)) {
					return imageCursor.getInt(image_id_column_index);
				}
			} else { //contact position
				return position;
			}
			return -1;
		}
		

		// create a new ImageView for each item referenced by the Adapter
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = null;
			
			if (convertView == null) {
				imageView = new ImageView(MultiImageChooserActivity.this);
			} else {
				imageView = (ImageView) convertView;
			}
			if(GameSettings.imagesSelected.get((int)getItemId(position)) != null) {
				setChecked(position, true);
				imageView.setBackgroundColor(SELECTED_BG_COLOR);
			} else {
				imageView.setBackgroundColor(Color.TRANSPARENT);
			}
			imageView.setImageBitmap(null);

			if (!imageCursor.moveToPosition(position) || 
					(isGallery && (image_id_column_index == -1 || image_orient_column_index == -1)) ||
					(!isGallery  && contact_image_column_index == -1)) {
				return imageView;
			}

			Bitmap image = getImage(position);
			if (image == null) {
				// The original image no longer exists, hide the image cell
				imageView.setVisibility(View.GONE);
				imageView.setClickable(false);
				imageView.setEnabled(false);
				return imageView;
			}

			Bitmap mutable = Bitmap.createBitmap(colWidth, colWidth, image.getConfig());

			canvas = new Canvas(mutable);

			RectF src = new RectF(0, 0, image.getWidth(), image.getHeight());
			RectF dst = new RectF(0, 0, canvas.getWidth(), canvas.getHeight());
			m.reset();
			m.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
			canvas.drawBitmap(image, m, null);

			image.recycle();
			image = null;

			imageView.setImageBitmap(mutable);

			return imageView;
		}
	}

	private Bitmap getImage(int position) {
		imageCursor.moveToPosition(position);
		Matrix m = new Matrix();
		Bitmap ret = null;
		if(isGallery) {
			Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail(
				getContentResolver(), imageCursor.getInt(image_id_column_index),
				MediaStore.Images.Thumbnails.MICRO_KIND, null);
			
			m.postRotate(imageCursor.getInt(image_orient_column_index));
			ret = Bitmap.createBitmap(thumb, 0, 0, thumb.getWidth(), thumb.getHeight(), m, true);
		} else {
			byte[] data = imageCursor.getBlob(contact_image_column_index);
			if(data == null) {
				ret = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
			} else {
				ret = BitmapFactory.decodeByteArray(data, 0, data.length);
			}
		}

		return ret;
	}

	private void setChecked(int position, boolean b) {
		checkStatus.put(position, b);
	}

	public boolean isChecked(int position) {
		boolean ret = checkStatus.get(position);
		return ret;
	}

	public void cancelClicked(View ignored) {
		setResult(RESULT_CANCELED);
		finish();
	}

	public void selectClicked(View ignored) {
		Bundle res = new Bundle();
//		res.putParcelableArrayList(AddPhotosActivity.IMAGES, new ArrayList<Bitmap>(images));
//		res.putSparseParcelableArray(AddPhotosActivity.IMAGES, images);
		if (imageCursor != null) {
			res.putInt("TOTALFILES", imageCursor.getCount());
		}
		Intent data = new Intent();
		data.putExtras(res);
		this.setResult(RESULT_OK, data);

		finish();
	}

	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		Bitmap image = getImage(position);
		
		if (image == null) {
			return;
		}
		boolean isChecked = !isChecked(position);
		if (!unlimitedImages && maxImagesLeft == 0 && isChecked) {
			return;
		}

		if (isChecked) {
			GameSettings.imagesSelected.put((int) id, image);
			maxImagesLeft--;
			view.setBackgroundColor(SELECTED_BG_COLOR);
		} else {
			GameSettings.imagesSelected.remove((int) id);
			maxImagesLeft++;
			view.setBackgroundColor(Color.TRANSPARENT);
		}

		setChecked(position, isChecked);
		acceptButton.setText(getResources().getString(GameSettings.imagesSelected.size() == 0 ? android.R.string.cancel : android.R.string.ok));
		//acceptButton.setEnabled(GameSettings.imagesSelected.size() != 0);
		updateLabel();

	}

	public Loader<Cursor> onCreateLoader(int cursorID, Bundle arg1) {
		Log.d(TAG, "onCreateLoader: " + cursorID);
		CursorLoader cl = null;

		ArrayList<String> img = new ArrayList<String>();
		switch (cursorID) {
			case CURSORLOADER_GALLERY:
				img.add(MediaStore.Images.Media._ID);
				img.add(MediaStore.Images.Media.ORIENTATION);
				
				Log.d(TAG, "Schema: " + MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				cl = new CursorLoader(MultiImageChooserActivity.this,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						img.toArray(new String[img.size()]), null, null, MediaStore.Images.Media._ID + " DESC");
				break;
			case CURSORLOADER_CONTACTS:
				img.add(Photo.PHOTO);
				cl = new CursorLoader(MultiImageChooserActivity.this,
						ContactsContract.Data.CONTENT_URI, img.toArray(new String[img.size()]), 
						Photo.PHOTO + " is not null AND " +
						ContactsContract.Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'", 
						null, ContactsContract.Contacts.DISPLAY_NAME);
				break;
		}

		return cl;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		Log.d(TAG, "onLoadFinished: " + loader.getId());
		Log.d(TAG, "Is the SD card mounted? " + Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()));
		if (cursor != null) {
			Log.d(TAG, "Cursor: " + cursor.toString() + "; items: " + cursor.getCount());
		} else {
			Log.d(TAG, "NULL cursor. This usually means there's no image database yet....");
			return;
		}

		imageCursor = cursor;
		switch (loader.getId()) {
			case CURSORLOADER_GALLERY:
				image_id_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
				image_orient_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
				break;
			case CURSORLOADER_CONTACTS:
				contact_image_column_index = imageCursor.getColumnIndex(Photo.PHOTO);
				break;
		}
		ia.notifyDataSetChanged();
	}

	public void onLoaderReset(Loader<Cursor> loader) {
		Log.d(TAG, "onLoaderReset: " + loader.getId());
		imageCursor = null;
//		switch (loader.getId()) {
//			case CURSORLOADER_GALLERY:
//				imageCursor = null;
//				break;
//			case CURSORLOADER_CONTACTS:
//				contactCursor = null;
//				break;
//			default:
//				break;
//		}
	}
	
	
}
